<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="form" :model="queryParams" size="small" :inline="true">
      <el-form-item v-for="item in docuFilterList" ref="from" :key="item.headerKey">
        <el-input v-model="item.value" :placeholder="'请输入' + item.data" style="width: 150px" @input="handleNameInput" />
      </el-form-item>

      <el-form-item v-if="docuFilterList.length > 0">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="30%" @close="cancel">
      <el-form ref="form" :model="schoolyear" label-width="80px" size="mini">
        <el-form-item v-for="item in headerData" :key="item.headerKey" :prop="item.headerKey" :label="item.name">
          <el-input v-model="data[item.headerKey]" :placeholder="'请输入' + item.name" style="width: 250px" />
        </el-form-item>

        <el-form-item v-if="docu.appendix == '1'">
          <span slot="label">
            <el-tooltip content="将所有附件打包成一个压缩包" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
            附件
          </span>
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="upload.url"
            :on-change="uploadChange"
            :file-list="fileList"
            :headers="upload.headers"
            :auto-upload="true"
            limit="1"
            :on-exceed="handleExceed"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
          >
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="centerbutton" /> -->
      <el-table-column
        v-for="item in headerData"
        :key="item.headerKey"
        :prop="item.headerKey"
        :label="item.name"
        align="center"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column prop="userName" label="创建人" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlechange(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteById(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { add, update, page, deleteById, query } from '@/api/docu_data.js'
import { query_docu } from '@/api/files.js'
import { query as filterQuery } from '@/api/docu_filter.js'
import { page_id } from '@/api/files_1.js'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      // 非单个禁用
      single: true,
      // 遮罩层
      loading: true,
      buttonState: '', // 存储按钮的状态
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      fileList: [],
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload'
      },
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      title: '',
      dialogVisible: false,
      sort: undefined,
      docu: {
        appendix: '0'
      },
      tableHeader: {
        name: '',
        sort: undefined
      },
      queryParams: {
        status: '',
        createTime: '', // 添加开始时间字段
        endTime: '' // 添加结束时间字段
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {},
      schoolyear: {},
      createTime: '',
      endTime: '',
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      headerData: [],
      tableKey: 0,
      list: null,
      total: 0,
      zlId: '',
      data: {},
      fileName: '',
      fileUrl: '',
      docuFilterList: []
    }
  },
  computed: {
    ...mapState(['name']),
    // 控制按钮是否禁用
    isFormDisabled() {
      // 当状态为启用（0）时，表单整体禁用
      return this.schoolyear.status === '0'
    },
    isTermDisabled() {
      // 单独控制学期学年项，状态为启用（0）时禁用
      return this.schoolyear.status === '0'
    }
  },

  mounted() {
    this.zlId = this.$route.params.id
    this.page() // 当页面加载完成后，发送异步请求，获取数据
    this.getHeader()
    this.queryDocu()
    this.queryDocuFilter()
  },

  methods: {
    queryDocuFilter() {
      filterQuery(this.zlId).then((res) => {
        this.docuFilterList = res.data
      })
    },
    cancel() {
      this.dialogVisible = false
      this.fileList = []
    },
    queryDocu() {
      query_docu(this.zlId).then((res) => {
        this.docu = res.data
      })
    },
    handleExport() {
      this.$confirm('是否导出所有数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 压缩包下载路径
          const downloadUrl =
            process.env.VUE_APP_BASE_API + '/data/export/' + this.zlId
          const fileName = `${this.docu.name + '-' + new Date().getTime()}.zip`

          // 调用下载方法
          this.download(downloadUrl, { method: 'POST' }, fileName)
        })
        .catch(() => {
          this.$message.info('已取消导出')
        })
    },
    uploadChange(file, fileList) {
      console.log(file.name, fileList)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleExceed(files, fileList) {
      this.$message.error('上传文件超出限制')
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.fileName = response.data.fileName
      this.fileUrl = response.data.fileUrl
      this.$message({ message: '上传成功', type: 'success' })
    },
    getHeader() {
      page_id(this.zlId)
        .then((res) => {
          if (res.code === 1) {
            // 确保响应成功
            this.headerData = res.data
          } else {
            console.error('API 请求未成功，响应码：', res.code)
          }
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    handleNameInput() {
      // 根据表头名称查找对应的表头序号
      const header = this.tableHeader.find(
        (header) => header.name === this.name
      )
      if (header) {
        this.sort = header.sort
      } else {
        this.sort = undefined
      }
    },
    handleSortInput() {
      // 根据表头序号查找对应的表头名称
      const header = this.tableHeader.find(
        (header) => header.sort === this.sort
      )
      if (header) {
        this.name = header.name
      } else {
        this.name = undefined
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 表单重置
    reset() {
      this.dataId = ''
      for (var item of this.headerData) {
        this.$set(this.data, item.headerKey, '')
      }
    },
    /** 修改表单按钮操作 */
    handlechange(row) {
      this.reset()
      this.dialogVisible = true
      this.title = '修改数据'
      this.dataId = row.id
      query(this.dataId).then((res) => {
        this.data = JSON.parse(res.data.data)
        this.fileList.push({
          name: res.data.fileName,
          url: res.data.fileUrl
        })
      })
    },
    /** 导出按钮操作 */
    handleDelete(row) {
      // const userIds = row.userId || this.ids
      // this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
      //   return delUser(userIds)
      // }).then(() => {
      //   this.getList()
      //   this.$modal.msgSuccess('删除成功')
      // }).catch(() => { })
    },
    // 查询分页数据
    page() {
      this.loading = true
      const requestData = {
        current: this.current,
        docuId: this.zlId,
        pageSize: this.pageSize
      }
      for (const docuFilter of this.docuFilterList) {
        if (docuFilter.value) {
          requestData[docuFilter.headerKey] = docuFilter.value
        }
      }

      page(requestData)
        .then((res) => {
          this.totalCount = res.data.total
          const dataList = res.data.records
          this.tableData = []
          for (const item of dataList) {
            const data = JSON.parse(item.data)
            data.id = item.id
            data.userName = item.userName
            data.createTime = item.createTime
            data.updateTime = item.updateTime
            this.tableData.push(data)
          }
          this.loading = false
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    handleAdd() {
      this.reset()
      this.dialogVisible = true
      this.title = '新增数据'
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = []
      this.page()
    },
    // 添加数据
    submit() {
      let operator
      console.log('this.data', this.data)
      const requestData = {
        docuId: this.zlId,
        data: JSON.stringify(this.data)
      }
      if (this.docu.appendix == '1') {
        requestData['fileName'] = this.fileName
        requestData['fileUrl'] = this.fileUrl
      }

      if (this.dataId) {
        requestData['id'] = this.dataId
        // 修改
        operator = update(requestData)
      } else {
        operator = add(requestData)
      }

      operator.then((resp) => {
        if (resp.code == '1') {
          this.$message({ message: '保存成功', type: 'success' })
          this.page()
        } else {
          this.$message.error(resp.msg)
        }
        this.dialogVisible = false
        this.fileList = []
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    deleteById(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 2. 发送AJAX请求
          deleteById(row.id).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },

    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}
</style>
